﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Skyhook.Logic.VisualControllers;
using Microsoft.Xna.Framework;
using Skyhook.Core;
using Skyhook.Resources;
using Skyhook.AI.Animators;

namespace Skyhook.Logic.Units
{
    class Animation : ILogic
    {
        AnimationVisualController Visual = null;
        LoopIntegerAnimator Animator = null;
        LoopInteger Frame = null;
        IObjectController AnimationObject = null;

        private Animation() :
            base()
        {
        }

        public Animation(string assetname, float startx, float starty):
            base()
        {
            IVisualObject visual = VisualsFactory.CreateCommonVisual(assetname);
            Visual = new AnimationVisualController(assetname, visual);

            AnimationObject = ObjectsEngine.CreateObject(this,visual);
            AnimationObject.Put(startx, starty);

            Frame = new LoopInteger(0, Visual.FramesCount);
            Frame.OnChange += UpdateFrame;

            Animator = new LoopIntegerAnimator(Frame);
            Animator.OnFinish += AutoRemove;
            Animator.RotateDelay = 1.0f;
            Animator.DestinationValue = Visual.FramesCount - 1;
        }

        void UpdateFrame(int value)
        {
            Visual.Frame = value;
        }

        public void Start()
        {
            Animator.StartAnimation();
        }

        public void Update(float elapsedticks)
        {
            if (!Animator.IsFinished)
            {
                Animator.Update(elapsedticks);
            }
        }

        void AutoRemove()
        {
            AnimationObject.Delete();
            AnimationObject = null;
        }

        static public Animation None = new Animation();
    }
}
